<?php
// 应用公共文件

/**
 * @param $info
 * @param int $status
 * @param null $url
 * @return array
 * 生成消息数组
 */
function get_msg($info, $status = 0, $url = null)
{
    return ['status' => $status, 'info' => $info, 'url' => $url];
}

/**
 * 根据级别得到对应的报单额度
 * @param $level
 * @return mixed
 */
function get_billmoney($level)
{
    $levelMoney = user_level_bonus_format(get_bonus_rule('level_money'));
    return $levelMoney[$level][2];
}

/**
 * 判断是否是微信
 * @return bool
 */
function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 根据报单级别得到报单中心的名字
 * @param $bill
 * @return mixed
 */
function getBillName($bill)
{
    $bill_levels = config('BILLLEVELS');
    return $bill_levels[$bill];
}

/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}

/**
 * @param $type
 * @return mixed
 * 获取配置
 */
function get_config($type)
{
    return \app\common\model\Bconfig::cache(true)->limit(1)->value($type);
}

function get_num($num_header = 'HD')
{
    $id = $num_header . rand(100000, 999999);
    $user = \app\common\model\UserRelation::where('user_num', $id)->find();
    while ($user) {
        $id = $num_header . rand(100000, 999999);
        $user = \app\common\model\UserRelation::where('user_num', $id)->find();
    }
    return $id;
}

/**
 *打印变量
 * @param $str
 */
function p($str)
{
    echo '<pre>';
    print_r($str);
    echo '</pre>';
    die;
}

/**
 * 得到会员的报单额
 * @param $uid
 * @return bool
 */
function get_bill_money($rank)
{
    $level_money_arr = user_level_bonus_format(get_bonus_rule('level_money'));
    return $level_money_arr[$rank][2];
}

/**
 * 加密函数
 * @param $str
 * @param string $key
 * @return string
 */
function think_ucenter_md5($str, $key = 'ThinkUCenter')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 会员登录日志
 * @param null $action
 * @param null $model
 * @param null $record_id
 * @param null $user_id
 * @return string
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null)
{

    //参数检查
    if (empty($action) || empty($model) || empty($record_id)) {
        return '参数不能为空';
    }
    if (empty($user_id)) {
        $user_id = is_login();
    }
//    //查询行为,判断是否执行
//    $action_info = \think\Db::table('zx_action_log')->getByName($action);
//    if ($action_info['status'] != 1) {
//        return '该行为被禁用或删除';
//    }
//
//    //插入行为日志
//    $data['action_id'] = $action_info['id'];
    $data['user_id'] = $user_id;
    $data['action_ip'] = ip2long(get_client_ip());
    $data['model'] = $model;
    $data['record_id'] = $record_id;
    $data['create_time'] = NOW_TIME;

    //解析日志规则,生成日志备注
    if (!empty($action_info['log'])) {
        if (preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)) {
            $log['user'] = $user_id;
            $log['record'] = $record_id;
            $log['model'] = $model;
            $log['time'] = NOW_TIME;
            $log['data'] = array('user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => NOW_TIME);
            foreach ($match[1] as $value) {
                $param = explode('|', $value);
                if (isset($param[1])) {
                    $replace[] = call_user_func($param[1], $log[$param[0]]);
                } else {
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] = str_replace($match[0], $replace, $action_info['log']);
        } else {
            $data['remark'] = $action_info['log'];
        }
    } else {
        //未定义日志规则，记录操作url
        $data['remark'] = '操作url：' . $_SERVER['REQUEST_URI'];
    }

    \think\Db::table('zx_action_log')->insert($data);

    if (!empty($action_info['rule'])) {
        //解析行为
        $rules = parse_action($action, $user_id);

        //执行行为
        $res = execute_action($rules, $action_info['id'], $user_id);
    }
}

/**
 * 手机
 * @return bool
 */
function isMobile()
{
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    //此条摘自TPM智能切换模板引擎，适合TPM开发
    if (isset ($_SERVER['HTTP_CLIENT']) && 'PhoneClient' == $_SERVER['HTTP_CLIENT'])
        return true;
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
        );
        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

/**
 * 根据用户ID获取用户名
 * @param  integer $uid 用户ID
 * @return string       用户名
 */
function get_username($uid = 0)
{
    static $list;
    if (!($uid && is_numeric($uid))) { //获取当前登录用户名
        return $_SESSION['onethink_home']['user_auth']['username'];
    }

    /* 获取缓存数据 */
    if (empty($list)) {
        $list = S('sys_active_user_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if (isset($list[$key])) { //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $User = new User\Api\UserApi();
        $info = $User->info($uid);
        if ($info && isset($info[1])) {
            $name = $list[$key] = $info[1];
            /* 缓存用户 */
            $count = count($list);
            $max = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_active_user_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

/**
 * 生成系统AUTH_KEY
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function build_auth_key()
{
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // $chars .= '`~!@#$%^&*()_+-=[]{};:"|,.<>/?';
    $chars = str_shuffle($chars);
    return substr($chars, 0, 40);
}

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_login()
{
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

/**
 * 数据签名认证
 * @param  array $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data)
{
    //数据类型检测
    if (!is_array($data)) {
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 是否需要提现密码验证
 * @return mixed
 */
function is_sndpsd()
{
    $ifpsd = session('ifpsd');
    return $ifpsd;
}

function get_new_user($member)
{
    $position = strpos($member['usernumber'], '_');
    if ($position > 0) {
        $member['usernumber'] = substr_replace($member['usernumber'], '', $position);
    } else {
        $member['usernumber'] = $member['usernumber'];
    }
    return $member;
}

function get_new_userb($bmember)
{
    if (!$bmember) {
        return [];
    } else {
        $position = strpos($bmember['usernumber'], '_');
        if ($position > 0) {
            $bmember['usernumber'] = substr_replace($bmember['usernumber'], '', $position);
        } else {
            $bmember['usernumber'] = $bmember['usernumber'];
        }
        return $bmember;
    }
}

/**
 * 根据会员id号得到会员的编号
 * @param $uid
 * @return array|null|string
 */
function getInfo($field, $uid)
{
    if ($uid == 0) {
        $msg = '公司';
    } else {
        $userInfo = \think\Db::name('member')->where('uid', $uid)->find();
//        if ($field == 'usernumber') {
//            $userInfo = get_new_user($userInfo);
//        }
        $msg = $userInfo[$field];
    }
    if ($msg) {
        return $msg;
    } else {
        return '暂无';
    }

}

function getManagerInfo($field, $mid)
{
    if ($mid == 0) {
        $msg = '公司';
    } else {
        $managerInfo = Db('manager')->where('mid', $mid)->find();
        $msg = $managerInfo[$field];
    }
    if ($msg) {
        return $msg;
    } else {
        return '暂无';
    }

}

/**
 * 获取规则
 * @param unknown $field
 * @param number $id
 */
function get_bonus_rule($field = '', $id = 1)
{
    $rule = \think\Db::name('bonus_rule')->where(array('id' => $id))->find();
    if (empty($field)) {
        return $rule;
    } else {
        return $rule[$field];
    }

}

function get_user_level_money($level, $bonusRole, $str, $key = 2)
{
    $level_money = $bonusRole[$str];
    $user_level_money = user_level_bonus_format($level_money);
    return $user_level_money[$level][$key];
}

function user_level_bonus_format($string)
{
    $arr = array_filter(explode(',', $string));

    $count = count($arr);
    // 弹出最后一个元素
    for ($i = 0; $i < $count; $i++) {
        $result = explode(':', $arr[$i]);
        $count1 = count($result);
        for ($j = 0; $j < $count1; $j++) {
            $myresult[$result[0]][$j + 1] = $result[$j];
        }
    }
    return $myresult;
}

/**
 * 后台登录
 * @return int
 */
function is_admin_login()
{
    $user = session('admin_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('admin_auth_sign') == data_auth_sign($user) ? $user['mid'] : 0;
    }
}

/**
 * 下边会员在父节点中的区间(按时间顺序的左区第一人)
 * @param $user
 * @param $puser
 * @return int
 */
function getZone($user, $puser)
{
    $left = ',' . $puser['uid'] . ':1,';
    $position1 = stripos($user['parentareas'], $left);
    if ($position1 !== false) {
        return 1;
    }
    $right = ',' . $puser['uid'] . ':2,';
    $position2 = stripos($user['parentareas'], $right);
    if ($position2 !== false) {
        return 2;
    } else {
        return false;
    }
}

/**
 * @param $agentid
 * @return mixed|string
 */
function getAgent($agentid)
{
    if ($agentid <= 0) {
        return '无代理区域';
    }
    $area = Db('district')->where('id', $agentid)->find();
    if ($area['level'] == 3) {
        $parea = Db('district')->where('id', $area['pid'])->find();
        $pparea = Db('district')->where('id', $parea['pid'])->find();
        $address = $pparea['name'] . $parea['name'] . $area['name'];
    } elseif ($area['level'] == 2) {
        $parea = Db('district')->where('id', $area['pid'])->find();
        $address = $parea['name'] . $area['name'];
    } else {
        $address = $area['name'];
    }
    return $address;
}

/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @author static7
 */
function exportExcel($expTitle, $expCellName, $expTableData)
{
    $fileName = $expTitle . date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    vendor("PHPExcel.PHPExcel");

    $objPHPExcel = new \PHPExcel();

    /*设置默认样式*/
    $objPHPExcel->getDefaultStyle()->getFont()->setSize(13);//设置表格默认样式
    $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//设置表格默认样式
    $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setWrapText(true);//换行
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);//设置行高
    $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);//设置单元格宽

    $cellName = range('A', 'Z');

    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16)->setBold(true);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle);

    $objPHPExcel->getActiveSheet()->getStyle($cellName[0] . '2:' . $cellName[$cellNum - 1] . '2')->getFont()->setBold(true);
    for ($i = 0; $i < $cellNum; $i++) {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for ($i = 0; $i < $dataNum; $i++) {
        $objPHPExcel->getActiveSheet()->getRowDimension($i + 3)->setRowHeight(30);
        for ($j = 0; $j < $cellNum; $j++) {
            $objPHPExcel->getActiveSheet(0)->setCellValueExplicit($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
        }
    }

    header('pragma:public');
    header('Content-type:applicationnd.ms-excel;charset=utf-8;name="' . $expTitle . '.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    ob_end_clean();
    $objWriter->save('php://output');
    exit;
}

function parentids_format($string)
{
    $arr = str2arr($string);

    $count = count($arr);
    // 弹出最后一个元素
    for ($i = 0; $i < $count; $i++) {
        $result = explode(':', $arr[$i]);
        if ($result[1] == 1) {
            $myresult['array_1'][] = $result[0];
        }
        if ($result[1] == 2) {
            $myresult['array_2'][] = $result[0];
        }

    }
    return $myresult;
}

/**
 *  二维数组验证一个值是否存在
 * @param unknown $value
 * @param unknown $array
 * @return boolean
 */
function deep_in_array($value, $array)
{
    foreach ($array as $item) {
        if (!is_array($item)) {
            if ($item == $value) {
                return true;
            } else {
                continue;
            }
        }

        if (in_array($value, $item)) {
            return true;
        } else if (deep_in_array($value, $item)) {
            return true;
        }
    }
    return false;
}

/**
 * 查找接点位
 * @param int $uid
 * @return int|mixed
 */
function getPosition($uid = 1)
{
    $pinfo = Db('member')->where(array('uid' => $uid))->find();
    if ($pinfo['znum'] < 2) {
        return $uid;
    } else {
        if ($uid == 1) {
            $parentids = ',' . $uid . ',';
        } else {
            $parentids = $pinfo['parentids'] . $uid . ',';
        }
        $map['znum'] = array('lt', 2);
//        $map['status'] = 1;
        $map['parentids'] = array('like', $parentids . "%");
        $minpdeep = Db('Member')->where($map)->min('pdeep');
        $map['pdeep'] = $minpdeep;
        $members = Db('Member')->field('zid')->where($map)->select();
        $arr = [];
        foreach ($members as $v) {
            $arr[] = $v['zid'];
        }
        $minzid = min($arr);
        $map['zid'] = $minzid;
        $minuid = Db('Member')->where($map)->value('uid');
        if (empty($minuid)) {
            $minuid = $uid;
        }
        return $minuid;
    }
}

function xs2arr()
{
    $xs = '赵 钱 孙 李 周 吴 郑 王 冯 陈 褚 卫
			蒋 沈 韩 杨 朱 秦 尤 许 何 吕 施 张
			孔 曹 严 华 金 魏 陶 姜 戚 谢 邹 喻
			柏 水 窦 章 云 苏 潘 葛 奚 范 彭 郎
			鲁 韦 昌 马 苗 凤 花 方 俞 任 袁 柳
			酆 鲍 史 唐 费 廉 岑 薛 雷 贺 倪 汤
			滕 殷 罗 毕 郝 邬 安 常 乐 于 时 傅
			皮 卞 齐 康 伍 余 元 卜 顾 孟 平 黄
			和 穆 萧 尹 姚 邵 湛 汪 祁 毛 禹 狄
			米 贝 明 臧 计 伏 成 戴 谈 宋 茅 庞
			熊 纪 舒 屈 项 祝 董 梁 杜 阮 蓝 闵
			席 季 麻 强 贾 路 娄 危 江 童 颜 郭
			梅 盛 林 刁 锺 徐 邱 骆 高 夏 蔡 田
			樊 胡 凌 霍 虞 万 支 柯 昝 管 卢 莫
			经 房 裘 缪 干 解 应 宗 丁 宣 贲 邓
			郁 单 杭 洪 包 诸 左 石 崔 吉 钮 龚
			程 嵇 邢 滑 裴 陆 荣 翁 荀 羊 於 惠
			甄 麴 家 封 芮 羿 储 靳 汲 邴 糜 松
			井 段 富 巫 乌 焦 巴 弓 牧 隗 山 谷
			车 侯 宓 蓬 全 郗 班 仰 秋 仲 伊 宫
			宁 仇 栾 暴 甘 钭 历 戎 祖 武 符 刘
			景 詹 束 龙 叶 幸 司 韶 郜 黎 蓟 溥
			印 宿 白 怀 蒲 邰 从 鄂 索 咸 籍 赖
			卓 蔺 屠 蒙 池 乔 阳 郁 胥 能 苍 双
			闻 莘 党 翟 谭 贡 劳 逄 姬 申 扶 堵
			冉 宰 郦 雍 却 璩 桑 桂 濮 牛 寿 通
			边 扈 燕 冀 僪 浦 尚 农 温 别 庄 晏
			柴 瞿 阎 充 慕 连 茹 习 宦 艾 鱼 容
			向 古 易 慎 戈 廖 庾 终 暨 居 衡 步
			都 耿 满 弘 匡 国 文 寇 广 禄 阙 东
			欧 殳 沃 利 蔚 越 夔 隆 师 巩 厍 聂
			晁 勾 敖 融 冷 訾 辛 阚 那 简 饶 空
			曾 毋 沙 岳 养 鞠 须 丰 巢 关 蒯 相
			查 后 荆 红 游 竺 权 逮 盍 益 桓 公
			万俟 司马 上官 欧阳 夏侯 诸葛 闻人 东方 赫连 皇甫 尉迟 公羊
			澹台 公冶 宗政 濮阳 淳于 单于 太叔 申屠 公孙 仲孙 轩辕 令狐
			钟离 宇文 长孙 慕容 司徒 司空 ';
    $xs = preg_replace("/[\s]+/is", " ", $xs);
    $xs_arr = str2arr($xs, ' ');
    return $xs_arr;
}

function xm2arr()
{
    $xs = '昊强 烨伟 苑博  鹏涛 炎彬  鹤轩 伟泽 熠彤  鸿煊 博涛 苑杰 黎昕 烨霖  哲瀚 雨泽 鹤轩 建辉
			雅琳 梦洁 凌薇 美莲  雅静  雪丽  依娜  雅芙 雨婷 曼婷 雪慧 淑颖 钰彤 璟雯 天瑜 婧琪 溶月
			素菲 诗涵 宁馨 妙菱 心琪';
    $xs = preg_replace("/[\s]+/is", " ", $xs);
    $xs_arr = str2arr($xs, ' ');
    return $xs_arr;
}

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str 要分割的字符串
 * @param  string $glue 分割符
 * @return array
 */
function str2arr($str, $glue = ',')
{
    return array_values(array_filter(explode($glue, $str)));
}

/**
 * 检测当前用户是否为超级管理员
 * @return boolean true-管理员，false-非管理员
 */
function is_administrator($uid = null)
{
    $uid = is_null($uid) ? is_admin_login() : $uid;
    $manager = Db('manager')->find($uid);
    $first = model('manager')->order('mid asc')->find();
    if ($manager['mname'] == $first->mname) {
        return true;
    } else {
        return false;
    }
}


/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map 映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 */
function int_to_string(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿')))
{
    if ($data === false || $data === null) {
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row) {
        foreach ($map as $col => $pair) {
            if (isset($row[$col]) && isset($pair[$row[$col]])) {
                $data[$key][$col . '_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

function get_cover($cover_id, $field = null)

{

    if (empty($cover_id)) {

        return false;

    }

    $picture = \think\Db::name('picture')->where(array('status' => 1))->find($cover_id);
    if (is_bool(strpos($picture['path'], 'http://'))) {
        $picture['path'] = fixAttachUrl($picture['path']);
    }
    return empty($field) ? $picture : $picture[$field];

}

function get_cover_replace($cover_id, $field = null)
{
    if (empty($cover_id)) {
        return false;
    }
    $picture = \think\Db::name('picture')->where(array('status' => 1))->find($cover_id);
    if (is_bool(strpos($picture['path'], 'http://'))) {
        $picture['path'] = fixAttachUrl($picture['path']);
    }
    return empty($field) ? $picture : str_replace('\\', '/', $picture[$field]);
}

/**对于附件来修正其url，兼容urlmodel2,sae
 * @param $url
 * @return string
 */
function fixAttachUrl($url)
{
    if (is_local()) {
        return str_replace('//', '/', getRootUrl() . $url); //防止双斜杠的出现
    } else {
        return $url;
    }

}

function is_local()
{
    $upload_driver = config('PICTURE_UPLOAD_DRIVER');
    return strtolower($upload_driver) == 'local' ? true : false;
}

/**
 * 会员的状态
 * @param $status
 * @return string
 */
function get_status($status)
{
    switch ($status) {

        case -1:
            $msg = "<span style='color:red;'>冻结</span>";
            break;
        case 0:
            $msg = "<span style='color:orange;'>未激活</span>";
            break;
        case 1:
            $msg = "<span style='color:red;'>未认证</span>";
            break;
        case 2:
            $msg = "<span style='color:orange;'>待审核</span>";
            break;
        case 3:
            $msg = "<span style='color:green;'>已认证</span>";
            break;
    }
    return $msg;
}

/**
 * 财务流水
 * @param $type
 * @param $touid
 * @param $fromuid
 * @param $money
 * @param null $op
 * @return mixed
 */
function money_change($type, $touid, $fromuid, $money, $op = '', $remark = '')
{
    $data['userid'] = $fromuid;
    $data['targetuserid'] = $touid;

    $data['recordtype'] = $type['recordtype'];
    $data['moneytype'] = $type['moneytype'];
    $data['changetype'] = $type['changetype'];

    $data['money'] = $money['money'];
    $data['hasmoney'] = $money['hasmoney'];
    if (isset($money['fee_money'])) {
        $data['fee_money'] = $money['fee_money'];
    }
    if (isset($money['point_money'])) {
        $data['point_money'] = $money['point_money'];
    }
    if (isset($money['game_money'])) {
        $data['game_money'] = $money['game_money'];
    }
    if (isset($money['shop_money'])) {
        $data['shop_money'] = $money['shop_money'];
    }
    if (isset($money['othermoney'])) {
        $data['othermoney'] = $money['othermoney'];
    }
    if (!empty($op)) {
        $data['op'] = $op;
    }
    if (!empty($remark)) {
        $data['remark'] = $remark;
    }
    $data['createtime'] = time();
    $result = \think\Db::name('money_change')->insert($data);
    return $result;
}

/**
 * 公司
 * @return mixed
 */
function get_com()
{
    $res['uid'] = 0;
    $res['usernumber'] = '0';
    return $res;
}

/**
 * 会员级别
 * @param $state
 * @return mixed
 */
function get_userrank($state)
{
    $levels = Db('levels')->field('id,name')->select();
    $data = [];
    foreach ($levels as $val) {
        $data[$val['id']] = $val['name'];
    }

    $text = $data[$state];
    return $text;
}

function get_level($state)
{
    $name = config('LEVELS');
    $color = Db('rank_color')->where('rank', $state)->where('types', 1)->value('fontcolor');

    $text = "<span style='color:{$color};'>{$name[$state]}</span>";
    return $text;
}

function format_num($num)
{
    $num = sprintf("%0.2f", $num);
    if ($num > 0) {
        $text = '<span style="color:red;display:inline;">' . $num . '</span>';
    } else {
        $text = $num;
    }
    return $text;
}

/**
 * 奖金变更类型
 * @param unknown $state
 * @return string
 */
function getChangeType($state)
{
    $change_type = config('CHANGETYPE');
    $text = $change_type[$state];
    return $text;
}

/**
 * 钱币类型
 * @param unknown $state
 * @return string
 */
function getMoneyType($state)
{
    $money_type = config('MONEYTYPE');
    $text = $money_type['title'][$state];
    $color = $money_type['color'][$state];
    $str = "<span style='color:%s;'>%s</span>";
    $text = sprintf($str, $color, $text);

    return $text;
}

/**
 * 生成一个随机订单号
 * @return [type] [description]
 */
function ordersn()
{
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2015] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999), rand(0, 99));
    return $orderSn;
}

function getCateName($id)
{
    $cateName = Db('shop_category')->where('id', $id)->value('title');
    if ($cateName) {
        return $cateName;
    } else {
        return '顶级分类';
    }
}

/**
 * 公司收入
 * @param number $changetype
 * @param unknown $hasmoney
 * @param number $taxmoney
 * @return boolean
 */
function finance1($hasmoney, $changetype = 20, $taxmoney = 0)
{
    $count_date = strtotime('today');
    $map['createtime'] = $count_date;

    $income_arr = array(4, 20, 28);
    if (!in_array($changetype, $income_arr)) {
        return false;
    }
    $finance = Db("Finance")->where($map)->find();
    if (!empty($finance)) {
        $data['income'] = $finance['income'] + $hasmoney;
        Db("Finance")->where($map)->update($data);
    } else {
        $data['createtime'] = $count_date;
        $data['income'] = $hasmoney;
        Db("Finance")->insert($data);
    }
}

/**
 * 公司支出
 * @param unknown $changetype
 * @param unknown $hasmoney
 * @param number $taxmoney
 * @return boolean
 */
function finance2($changetype, $hasmoney, $taxmoney = 0)
{
    $count_date = strtotime('today');
    $map['createtime'] = $count_date;
    $finance = Db("finance")->where($map)->find();
    $expend_arr = array(1, 2, 3, 4, 5, 6, 7);
    if (!in_array($changetype, $expend_arr)) {
        return false;
    }
    $bonus = 'bonus' . $changetype;
    if (!empty($finance)) {
        $data['expend'] = $finance['expend'] + $hasmoney;
        $data[$bonus] = $finance[$bonus] + $hasmoney;
        Db("Finance")->where($map)->update($data);
    } else {
        $data['createtime'] = $count_date;
        $data['expend'] = $hasmoney;
        $data[$bonus] = $hasmoney;
        Db("Finance")->insert($data);
    }
}

function create_order($uid = 0, $type = 1)
{
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $uCode = array('K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
    $len = count($yCode);
    $yu = $uid % $len;
    $ye = (intval(date('Y')) - 2014) % $len;
    $orderSn = $yCode[$ye] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999), rand(0, 99)) . $uCode[$yu] . $type;
    return $orderSn;
}

function getOrderType($id)
{
    $order = Db('shop_order')->where('id', $id)->find();
    switch ($order['status']) {
        case 1:
            $name = '待发货';
            break;
        case 2:
            $name = '待确认';
            break;
        case 3:
            $name = '已完成';
            break;
    }
    $lists = Db('shoplist')->where('orderid', $id)->select();
    foreach ($lists as $v) {
        if ($v['status'] == 5) {
            $name = '有申诉';
        }
    }

    return $name;
}

/**
 * 总投资
 * @param $uid
 * @return float|int
 */
function getInvest($uid, $tdeep)
{
    $tdeeps = config('TDEEPS');
    if ($tdeeps > 0) {
        $minTdeep = $tdeep + 1;
        $maxTdeep = $tdeep + $tdeeps;
        $map['tdeep'] = array(array('egt', $minTdeep), array('elt', $maxTdeep));
    }

    $map['tuijianids'] = array('like', '%,' . $uid . ',%');

    $sons = Db('member')->field('uid')->where($map)->select();
    if ($sons) {
        $money = Db('bonus_rule')->where('id', 1)->value('bmoney');
        $total1 = 0;
        $total2 = 0;

        foreach ($sons as $v) {
            $total1 += Db('reinvest')->where('uid', $v['uid'])->sum('money');
            $num = Db('bmember')->where('tuijianid', $v['uid'])->count();
            $total2 += $money * $num;
        }
        return format_num($total1 + $total2);
    } else {
        return 0.00;
    }

}

function getRecharge($uid, $tdeep)
{
    $tdeeps = config('TDEEPS');
    if ($tdeeps > 0) {
        $minTdeep = $tdeep + 1;
        $maxTdeep = $tdeep + $tdeeps;
        $map['tdeep'] = array(array('egt', $minTdeep), array('elt', $maxTdeep));
    }
    $map['tuijianids'] = array('like', '%,' . $uid . ',%');
    $sons = Db('member')->field('uid')->where($map)->select();
    if ($sons) {
        $total = 0;
        foreach ($sons as $v) {
            $total += Db('recharge')->where('userid', $v['uid'])->where('status', 1)->sum('money');
        }
        return format_num($total);
    } else {
        return 0.00;
    }

}


